package com.sxdx.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sxdx.common.Result;
import com.sxdx.entity.SysUser;
import com.sxdx.entity.dto.SysUserDto;
import com.sxdx.mapper.SysUserMapper;
import com.sxdx.service.ISysUserService;
import com.sxdx.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.sxdx.utils.RedisConstants.LOGIN_USER_KEY;
import static com.sxdx.utils.RedisConstants.LOGIN_USER_TTL;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    //拦截器对象是自己创建的，无法纳入spring管理，所以使用StringRedisTemplate时需要用构造函数注入
    @Resource
    public StringRedisTemplate stringRedisTemplate;

    @Autowired
    SysUserMapper sysUserMapper;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头中的token
        String token = request.getHeader("Authorization");
        //2.判断token是否为空
        if (StrUtil.isBlank(token)){
            //不存在，拦截
            sendResponse(response,Result.RE410());
            return false;
        }
        token=token.substring(7);
        //3.基于token获取redis中的用户
//        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY + token);
        String userId=stringRedisTemplate.opsForValue().get(token);
        //4.判断用户是否存在
        if (StrUtil.isBlank(userId)){
            sendResponse(response,Result.RE411());
        }
        SysUser user = getUserById(userId);
        if (user == null) {
            sendResponse(response,Result.RE411());
        }

        //6.保存用户信息到ThreadLocal中
        SysUserDto sysUserDto=new SysUserDto();
        BeanUtils.copyProperties(user,sysUserDto);
        UserHolder.saveUser(sysUserDto);
        //7.刷新token有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY + token,LOGIN_USER_TTL, TimeUnit.MINUTES);
        return true;
    }



    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        UserHolder.removeUser();
    }

    public  void sendResponse(HttpServletResponse response,Result<?> result) {
        try {
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            PrintWriter writer = response.getWriter();
            String json = JSON.toJSONString(result);
            writer.write(json);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("向响应体中写入数据失败");
        }
    }

    private SysUser getUserById(String userId){
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserId,userId);
        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        return sysUser;
    }
}
